<template>
  <div>
    <!-- <h1>已投产</h1> -->
    <!-- 搜索 -->
    <!-- <el-card class="topcardstyle">
      <el-form
        :inline="true"
        :model="formInline"
        class="demo-form-inline formstyle"
      >
        <el-form-item :label="$t('tasksheet.startDate')">
          <el-date-picker
            v-model="formInline.Order_Start_Date"
            type="date"
            :placeholder="$t('tasksheet.startDateselect')"
            format="DD-MM-YYYY"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item :label="$t('tasksheet.orderType')">
          <el-select
            v-model="formInline.order_type"
            :placeholder="$t('tasksheet.orderTypeselect')"
            style="width: 240px"
            clearable
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchBtn">{{
            $t("entirety.search")
          }}</el-button>
          <el-button type="primary" @click="resetBtn">{{
            $t("entirety.reset")
          }}</el-button>

          <el-button type="primary" @click="printBtn">{{
            $t("entirety.print")
          }}</el-button>
        </el-form-item>
      </el-form>
    </el-card> -->

    <!-- 权限按钮 -->
    <el-card class="maincardstyle">
      <el-button type="primary" @click="searchBtn" style="margin-bottom: 20px">
        {{ $t("entirety.refresh") }}
      </el-button>

      <!-- 表格 -->
      <el-row>
        <el-table
          :data="displayData"
          stripe
          height="65vh"
          border
          style="width: 100%"
          :header-cell-style="{ background: '#fafafa', color: '#333' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column align="center" type="selection" fixed="left" />
          <el-table-column align="center" type="index" fixed="left" />
          <el-table-column
            align="center"
            prop="orderNo"
            :label="$t('tasksheet.orderNo')"
            fixed="left"
            min-width="100"
          >
            <template #default="scope">
              <!-- <el-text type="primary" @click="orderNoBtn(scope.row)"> -->
              {{ formatOrderNo(scope.row.orderNo) }}
              <!-- </el-text> -->
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="tankNo"
            :label="$t('tasksheet.lineNo')"
            min-width="60"
          />
          <el-table-column
            align="center"
            prop="batchNo"
            :label="$t('tasksheet.batchNo')"
            min-width="120"
          />
          <el-table-column
            align="center"
            prop="matlNo"
            :label="$t('tasksheet.matLNo')"
            min-width="120"
          />
          <el-table-column
            align="center"
            prop="matlDes"
            :label="$t('tasksheet.matlDes')"
            min-width="200"
          />
          <el-table-column
            align="center"
            prop="qty"
            :label="$t('tasksheet.qty')"
            min-width="120"
          />
          <el-table-column
            align="center"
            prop="recipeNo"
            :label="$t('tasksheet.recipeNo')"
            min-width="120"
          />
          <el-table-column
            align="center"
            prop="productionVersion"
            :label="$t('tasksheet.productionVersion')"
            min-width="120"
          />
          <!-- <el-table-column
          align="center"
          prop="mrp"
          :label="$t('tasksheet.mrp')"
          min-width="200"
        /> -->
          <!-- <el-table-column
          align="center"
          prop="Order_End_Date"
          :label="$t('tasksheet.orderEndDate')"
          min-width="200"
        />
        <el-table-column
          align="center"
          prop="start_time"
          :label="$t('tasksheet.startTime')"
          min-width="200"
        /> 
        <el-table-column
          align="center"
          prop="end_time"
          :label="$t('tasksheet.endTime')"
          min-width="200"
        /> -->
          <!-- <el-table-column
            align="center"
            prop="createTime"
            :label="$t('tasksheet.createTime')"
            min-width="200"
          /> -->
          <el-table-column
            align="center"
            fixed="right"
            :label="$t('entirety.handle')"
            min-width="150px"
          >
            <template #default="scope">
              <el-button
                icon="edit-pen"
                text
                type="primary"
                @click="PutintoproductionBtn(scope.row)"
                :disabled="scope.row.pwsStatus !== 0"
              >
                {{ $t("entirety.Putintoproduction") }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>

      <!-- 分页 -->
      <el-row>
        <div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[1, 10, 20, 30, 50, 100]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="countData"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-row>
    </el-card>

    <!-- 公司log -->
    <!-- <el-row>
    <div class="kx-log-box">
      技术支持：
      <img
        class="imgstyle"
        src="@/assets/images/kxauto.png"
        alt="描述图片的文字"
      />
      西安开轩自动化有限责任公司
    </div>
  </el-row> -->

    <!-- 弹窗 -->
    <form-dialog ref="formRef" />
  </div>
</template>

<script lang="ts" setup name="Tasksheek">
import { ref, reactive, onMounted } from "vue";
import router from "@/router"; //路由跳转
import { apiqueuelist, apiaddPwsQueue } from "@/api/tasksheet";
import { ElMessage, ElMessageBox } from "element-plus";
import emitter from "@/utils/eventbus"; //引入bus
// 引入子组件
import formDialog from "./form.vue";
const formRef = ref();

const tableData = ref(); //table数组
// onMounted(() => {
//   searchBtn(); // 页面加载时自动获取数据
// });
// 搜索
const formInline = reactive({
  // Order_Start_Date: "2023-08-26", //2023-08-26
  Order_Start_Date: "", //2023-08-26
  order_type: "",
});

const options = [
  {
    value: "ZWSF",
    label: "乳胶漆半成品",
  },
  {
    value: "ZWFG",
    label: "乳胶漆成品",
  },
];

// 去掉前四个字符 0
const formatOrderNo = (orderNo: string) => {
  return orderNo.slice(5);
};

// 重置
const resetBtn = () => {
  formInline.Order_Start_Date = ""; //清空搜索内容
  formInline.order_type = "";
  tableData.value = [];
};
const orderNoList = ref([] as any);
const selectedRows = ref<any[]>([]); // 记录复选框选中的行
// 监听复选框的变化
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = [];
  selectedRows.value = val;
};

// 打印
const printBtn = () => {
  if (selectedRows.value.length == 0) {
    ElMessage.warning("请勾选要打印的电子单");
    // } else if (selectedRows.value.length == 1) {
    //   formRef.value.openDialog();
  } else {
    orderNoList.value = [];
    selectedRows.value.forEach((item: any) => {
      orderNoList.value.push(item.orderNo);
    });
    formRef.value.openDialog(orderNoList.value);
    // ElMessage.success(`共打印${selectedRows.value.length}条备料单`);
  }
};
// /* 分页 */
const displayData = ref([]); // 储存当前分页的table数据
const currentPage = ref(1); // 默认在第几页
const pageSize = ref(10); // 默认1页几条数据
const countData = ref(); //总条数
const small = ref(false);
const background = ref(false);
const disabled = ref(false);

// 更新当前需要显示到页面的数据
const updateDisplayData = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  displayData.value = tableData.value.slice(start, end); // 获取当前页数据
};


// 封装获取数据的函数（关键修改）
const fetchData = async () => {
  try {
    const res = await apiqueuelist(
      {
        createTime: "",
        id: null,
        lineNo: null,
        orderNo: "",
        pwsStatus: null,
        sequence: null,
      },
      currentPage.value, // 传入当前页码
      pageSize.value // 传入每页条数
    );

    if (res.code === 200) {
      tableData.value = res.rows.map((item) => ({
        ...item.pwsQueue,
        ...item.pwsTable,
      }));
      countData.value = res.total; // 更新总条数
      displayData.value = tableData.value; // 直接显示API返回的当前页数据
    } else {
      ElMessage.warning(res.msg);
    }
  } catch (err) {
    ElMessage.error(err.message);
  }
};

//每页条数变化（关键修改）
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
  fetchData(); // 重新获取数据
};

// 页码变化（关键修改）
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchData(); // 获取新页码的数据
};

// 搜索按钮（修改）
const searchBtn = () => {
  currentPage.value = 1; // 搜索时回到第一页
  fetchData();
};

// 初始化加载数据
onMounted(() => {
  fetchData();
});
// 预览
const orderNoBtn = (row: any) => {
  router.push({
    path: "/tasksheek/getProductionOrderView/index",
    query: { row: JSON.stringify(row) },
  });
  // const query = JSON.stringify(row);
  // router.push("/tasksheek/getProductionOrderView/index");
};

// // import { useTagsViewStore } from '@/layout/components/TagsView/index.vue'; // 引入 tagsViewStore
// import useTagsViewStore from "@/store/modules/tagsView";

// const orderNoBtn = (row: any) => {
//   const tagsViewStore = useTagsViewStore(); // 获取 tagsViewStore
//   const { order_No } = row; // 获取 order_No

//   // 格式化新的 tab 页信息
//   const view = {
//     fullPath: "/tasksheek/getProductionOrderView",
//     path: "/tasksheet/getProductionOrderView",
//     name: "Production Order View", // 使用唯一标识符（例如 OrderNo）
//     meta: { icon: "user", title: "Production Order View" },
//   };

//   // 添加到 tagsViewStore，管理 tab 页
//   tagsViewStore.addView(view); // 添加新 tab
//   // debugger;
//   // 路由跳转
//   router.push({
//     path: "/tasksheet/getProductionOrderView",
//     query: { row: JSON.stringify(row) },
//   });
// };

// import { useTagsViewStore } from '@/store/modules/tagsView'; // 引入 tagsViewStore

// // 添加标签
// const addTags = (route: any) => {
//   const tagsViewStore = useTagsViewStore();
//   const { name } = route;
//   if (name) {
//     tagsViewStore.addView(route);
//   }
// };

// const orderNoBtn = (row: any) => {
//   const { order_No } = row;

//   // 格式化新的 tab 页信息
//   const view = {
//     fullPath: "/tasksheek/getProductionOrderView",
//     path: "/tasksheet/getProductionOrderView",
//     name: 'Production Order View', // 使用唯一标识符（例如 OrderNo）
//     meta: { icon: "user", title: 'Production Order View' },
//   };

//   // 路由跳转
//   router.push({
//     path: "/tasksheet/getProductionOrderView",
//     query: { row: JSON.stringify(row) },
//   });

//   // 调用 addTags 来添加 tab
//   addTags(view);
// };

// 投入生产
const PutintoproductionBtn = (row: any) => {
  // router.push({
  //   path: "/tasksheet/getProductionOrder",
  //   query: { row: JSON.stringify(row) },
  // });

  ElMessageBox.alert("确认是否下发这条数据？", "提示", {
    confirmButtonText: "OK",
    callback: (action: Action) => {
      if (action === "confirm") {
        // 确保只有点击 "OK" 时才执行
        apiaddPwsQueue({
          id: row.pwsQueueId,
        })
          .then((res: any) => {
            if (res.code == 200) {
              ElMessage.success(res.msg);
              searchBtn(); //刷新
            } else {
              ElMessage.warning(res.msg);
            }
          })
          .catch((err) => {
            ElMessage.error(err.message);
          });
      }
    },
  });
};
</script>

<style scoped lang="scss">
::v-deep .el-card__body {
  padding: 0px;
}

.topcardstyle {
  padding: 10px 20px 10px !important;
  margin-bottom: 10px;
  // background-color: #eee;
}

.maincardstyle {
  padding: 20px;
}

.createbtnstyle {
  margin-bottom: 20px;
}

.inputstyle {
  width: 300px;
}

// 搜索
.demo-form-inline .el-name {
  --el-name-width: 220px;
}

.formstyle {
  margin-bottom: -18px;
}

// 分页
.demo-pagination-block {
  margin: 0 auto;
  margin-top: 15px;
  // margin-bottom: 35px;
}

// 小圆点
.istyleNo {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: red;
  border-radius: 50%;
  margin-right: 5px;
}

.istyleOk {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: green;
  border-radius: 50%;
  margin-right: 5px;
}

// 公司log
.kx-log-box {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  height: 20px;
  line-height: 20px;
  margin-top: 15px;

  // 图片
  .imgstyle {
    width: 40px;
  }
}
</style>
